package com.zyh.counselor.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zyh.common.annotation.Log;
import com.zyh.common.core.controller.BaseController;
import com.zyh.common.core.domain.AjaxResult;
import com.zyh.common.core.domain.entity.SysUser;
import com.zyh.common.core.page.TableDataInfo;
import com.zyh.common.enums.BusinessType;
import com.zyh.common.utils.SecurityUtils;
import com.zyh.common.utils.StringUtils;
import com.zyh.common.utils.poi.ExcelUtil;
import com.zyh.counselor.domain.Counselor;
import com.zyh.counselor.domain.CounselorVo;
import com.zyh.counselor.service.ICounselorService;
import com.zyh.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 咨询师信息Controller
 *
 * @author zhangyangheng
 * @date 2025-03-16
 */
@RestController
@RequestMapping("/counselor/counselor")
public class CounselorController extends BaseController {
    @Autowired
    private ICounselorService counselorService;

    @Autowired
    private ISysUserService userService;

    /**
     * 管理员撤销咨询师的咨询资格
     * @param counselorId
     * @return
     */
    @PutMapping("/updateStatus/{counselorId}")
    public AjaxResult updateStatus(@PathVariable("counselorId") Long counselorId) {
        return toAjax(counselorService.update(new LambdaUpdateWrapper<Counselor>()
                .eq(Counselor::getCounselorId, counselorId)
                .eq(Counselor::getCertificationStatus, "1")
                .eq(Counselor::getDelFlag, "0")
                .set(Counselor::getCertificationStatus, "2")));
    }

    /**
     * 查询所有的已认证的咨询师的基本信息和职业信息
     * 将咨询师和用户转成vo对象返回给前端
     *
     * @return
     */
    @GetMapping("/listCounselors")
    public AjaxResult listCounselors(Counselor CounselorVo) {
        LambdaQueryWrapper<Counselor> wrapper = new LambdaQueryWrapper<Counselor>()
                .eq(Counselor::getCertificationStatus, "1")
                // 查询不到自己
                .ne(Counselor::getUserId, SecurityUtils.getUserId())
                .eq(Counselor::getDelFlag, "0");
        // 条件查询
        if (StringUtils.isNotEmpty(CounselorVo.getTitle())) {
            wrapper.eq(Counselor::getTitle, CounselorVo.getTitle());
        }
        if (StringUtils.isNotEmpty(CounselorVo.getCertificationStatus())) {
            wrapper.eq(Counselor::getCertificationStatus, CounselorVo.getCertificationStatus());
        }
        List<Counselor> counselorList = counselorService.list(wrapper);
        // 没有数据
        if (Objects.isNull(counselorList) || counselorList.isEmpty()) {
            return AjaxResult.success();
        }
        Set<Long> ids = counselorList.stream().map(Counselor::getUserId).collect(Collectors.toSet());
        List<SysUser> userList = userService.listByIds(ids);
        List<CounselorVo> counselorVoList = counselorList.stream().map(counselor -> {
            // 创建Vo对象
            CounselorVo vo = new CounselorVo();

            // 复制对象
            BeanUtils.copyProperties(counselor, vo);

            // 查找匹配用户
            userList.stream()
                    .filter(user -> user.getUserId().equals(counselor.getUserId()))
                    .findFirst()
                    .ifPresent(user -> {
                        // 复制用户属性
                        vo.setUsername(user.getUserName());
                        vo.setNickname(user.getNickName());
                        vo.setEmail(user.getEmail());
                        vo.setPhonenumber(user.getPhonenumber());
                        vo.setSex(user.getSex());
                        vo.setAvatar(user.getAvatar());
                    });

            return vo;
        }).collect(Collectors.toList());
        return AjaxResult.success(counselorVoList);
    }

    /**
     * 管理员审核咨询师资格
     *
     * @param counselor
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/handleApplyFor")
    public AjaxResult handleApplyFor(@RequestBody Counselor counselor) {
        logger.info("handleApplyFor入参->{}", counselor);
        Long userId = counselor.getUserId();
        String status = counselor.getCertificationStatus();

        // 参数校验
        if (userId == null || StringUtils.isEmpty(status)) {
            return AjaxResult.error("参数不完整");
        }

        // 状态合法性校验
        if (!Arrays.asList("1", "2").contains(status)) {
            return AjaxResult.error("非法状态值");
        }

        // 审核不通过必须填写原因
        if ("2".equals(status) && StringUtils.isEmpty(counselor.getReason())) {
            return AjaxResult.error("请填写不通过原因");
        }
        LambdaUpdateWrapper<Counselor> wrapper = new LambdaUpdateWrapper<Counselor>()
                .eq(Counselor::getUserId, userId)
                .eq(Counselor::getCertificationStatus, "0") // 只处理待审核状态的记录
                .eq(Counselor::getDelFlag, "0")
                .set(Counselor::getUpdateBy, SecurityUtils.getUsername())
                .set(Counselor::getUpdateTime, new Date());

        // 根据状态设置不同字段
        if ("1".equals(status)) {
            wrapper.set(Counselor::getCertificationStatus, "1")
                    .set(Counselor::getReason, null); // 通过时清空原因
            SysUser user = userService.selectUserById(userId);
            if (user != null) {
                // 给用户添加咨询师角色
                userService.insertUserAuth(user.getUserId(), new Long[]{2L, 3L});
            }
        } else if ("2".equals(status)) {
            wrapper.set(Counselor::getCertificationStatus, "2")
                    .set(Counselor::getReason, counselor.getReason());
        }
        return counselorService.update(counselor, wrapper) ?
                AjaxResult.success("处理成功") :
                AjaxResult.error("处理失败（可能已被其他管理员处理）");
    }


    /**
     * 咨询师申请
     *
     * @param counselor
     * @return
     */
    @PostMapping("/handApply")
    public AjaxResult handApply(@RequestBody Counselor counselor) {
        logger.info("handApply入参->{}", counselor);
        Long userId = SecurityUtils.getUserId();
        Counselor serviceOne = counselorService.getOne(new LambdaQueryWrapper<Counselor>()
                .eq(Counselor::getUserId, userId)
                .eq(Counselor::getDelFlag, "0"));
        if (Objects.nonNull(serviceOne)) {
            // 如果是被拒绝状态，允许更新信息重新提交
            if ("2".equals(serviceOne.getCertificationStatus())) {
                counselorService.update(counselor, new LambdaUpdateWrapper<Counselor>()
                        .eq(Counselor::getCounselorId, serviceOne.getCounselorId())
                        .eq(Counselor::getDelFlag, "0")
                        .set(Counselor::getCertificationStatus, "0")
                        .set(Counselor::getReason, (String) null)
                        .set(Counselor::getUpdateBy, SecurityUtils.getUsername())
                        .set(Counselor::getUpdateTime, new Date()));
                return AjaxResult.success("重新提交成功！等待管理员审核", counselor);
            }
            return AjaxResult.error("您已有待审核的申请，请勿重复提交");
        } else {
            counselor.setUserId(userId);
            counselor.setCertificationStatus("0");
            counselor.setCreateBy(SecurityUtils.getUsername());
            counselor.setCreateTime(new Date());
            counselor.setDelFlag("0");
            counselorService.save(counselor);
            return AjaxResult.success("申请成功！等待管理员审核", counselor);
        }
    }

    /**
     * 获取咨询师信息
     *
     * @return
     */
    @GetMapping("/getById")
    public AjaxResult getById() {
        Counselor counselor = counselorService.getOne(new LambdaQueryWrapper<Counselor>()
                .eq(Counselor::getUserId, SecurityUtils.getUserId())
                .eq(Counselor::getDelFlag, "0"));
        return AjaxResult.success(counselor);
    }

    /**
     * 查询申请的咨询师信息列表
     */
    //@PreAuthorize("@ss.hasPermi('counselor:counselor:list')")
    @GetMapping("/list")
    public AjaxResult list() {
        List<Counselor> counselorList = counselorService.list(new LambdaQueryWrapper<Counselor>()
                .eq(Counselor::getCertificationStatus, "0")
                .eq(Counselor::getDelFlag, "0"));
        Map<String, List<?>> map = null;
        if (Objects.nonNull(counselorList)) {
            List<Long> ids = counselorList.stream().map(Counselor::getUserId).collect(Collectors.toList());
            List<SysUser> userList = new ArrayList<>();
            for (Long id : ids) {
                SysUser user = userService.selectUserById(id);
                if (Objects.nonNull(user)) {
                    userList.add(user);
                }
            }
            map = new HashMap<>();
            if (Objects.nonNull(userList)) {
                map.put("counselorList", counselorList);
                map.put("userList", userList);
            }
        }
        return AjaxResult.success(map);
    }

    /**
     * 导出咨询师信息列表
     */
    //@PreAuthorize("@ss.hasPermi('counselor:counselor:export')")
    @Log(title = "咨询师信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Counselor counselor) {
        List<Counselor> list = counselorService.selectCounselorList(counselor);
        ExcelUtil<Counselor> util = new ExcelUtil<Counselor>(Counselor.class);
        util.exportExcel(response, list, "咨询师信息数据");
    }

    /**
     * 获取咨询师信息详细信息
     */
    //@PreAuthorize("@ss.hasPermi('counselor:counselor:query')")
    @GetMapping(value = "/{counselorId}")
    public AjaxResult getInfo(@PathVariable("counselorId") Long counselorId) {
        Counselor counselor = counselorService.getOne(new LambdaQueryWrapper<Counselor>()
                .eq(Counselor::getCounselorId, counselorId)
                .eq(Counselor::getDelFlag, "0"));
        if (Objects.isNull(counselor)) {
            return AjaxResult.error("该咨询师信息不存在");
        }
        SysUser user = userService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserId, counselor.getUserId())
                .eq(SysUser::getDelFlag, "0"));
        CounselorVo vo = new CounselorVo();
        BeanUtils.copyProperties(counselor, vo);
        BeanUtils.copyProperties(user, vo);
        vo.setUsername(user.getUserName());
        vo.setNickname(user.getNickName());
        vo.setAddress(counselor.getAddress());
        return AjaxResult.success(vo);
    }

    /**
     * 新增咨询师信息
     */
    //@PreAuthorize("@ss.hasPermi('counselor:counselor:add')")
    @Log(title = "咨询师信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Counselor counselor) {
        return toAjax(counselorService.insertCounselor(counselor));
    }

    /**
     * 修改咨询师信息
     */
    //@PreAuthorize("@ss.hasPermi('counselor:counselor:edit')")
    @Log(title = "咨询师信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Counselor counselor) {
        return toAjax(counselorService.updateCounselor(counselor));
    }

    /**
     * 删除咨询师信息
     */
    //@PreAuthorize("@ss.hasPermi('counselor:counselor:remove')")
    @Log(title = "咨询师信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{counselorIds}")
    public AjaxResult remove(@PathVariable Long[] counselorIds) {
        return toAjax(counselorService.deleteCounselorByCounselorIds(counselorIds));
    }


}
